<?php

class MenuAdmin
{
    private $menu;
    private $_db;
    
    public function __construct()
    {
        $this->_db = Db::getInstance();
        $this->selectMenu();
    }
    
    private function selectMenu()
    {
        //var_dump($_GET);
        if (isset($_GET['menu']))
        {
            $menu = mysql_real_escape_string($_GET['menu']).'_menu';
            if ($this->_db->table_exists($menu))
            {
                $this->menu = $menu;
            }
        }
        else
        {
            $this->menu = 'def_menu';
        }
    }
    
    public function showMenu()
    {
        ob_start();
        $this->showMain();
        $content = ob_get_clean();
        return $content;
    }
    
    private function showChild ($parent)
    {
        $res = $this->_db->qr("select * from `".$this->menu."` where `parent` = '".$parent."'");
        //var_dump($res);
        if ($res != null)
        {
            echo '<ul>';
            foreach ($res as $r)
            {        
                echo '<li><div><table><tr><td><h3>'.$r['name'].'</h3></td><td class="link">'.$r['link'].'</td>  <td width="220"><button class="btn primary">Редактировать</button> <button class="btn danger">Удалить</button></td></tr></table></div></li>';
                $this->showChild($r['id']);
            }
            echo '</ul>';
        }
        
    }
    
    private function showMain()
    {
        $res = $this->_db->qr("select * from `".$this->menu."` where `parent` = 0");
        //var_dump($res);
        if ($res != null)
        {   
            echo '<ul class="menu" id="sortable">';
            foreach ($res as $r)
            {        
                echo '<li><div><table><tr><td><h3>'.$r['name'].'</h3></td><td class="link">'.$r['link'].'</td>  <td width="220"><button class="btn primary">Редактировать</button> <button class="btn danger">Удалить</button></td></tr></table></div></li>';
                $this->showChild($r['id']);
            }
            echo '</ul>';
            
        }
    }
    
    
}